<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\View; //模板引擎
use app\common\Base;
use think\facade\Request;
use think\exception\ValidateException;
use app\model\Admin as AdminMod;
use app\model\AdminRole;
use app\validate\LoginVal;
use app\validate\AdminVal;

/**
 * @name 管理员
 */
class Admin extends Base
{
    /**
     * @name 管理员列表
     */
    public  function list()
    {
        if (request()->isPost()) {
            $param = Request::param();
            $w = '';
            if (isset($param['name']) && $param['name'] != '') {
                $w = "name like '%" . $param['name'] . "%'";
            }
            $list = AdminMod::list($w, (int)$param['limit'], (int)$param['page']);
            return getBack(0, '', $list['data'], $list['count']);
        }
        return View::fetch();
    }

    /**
     * @name 管理员添加
     */
    public  function add()
    {
        $role = AdminRole::select();
        View::assign('select', $role);
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(LoginVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $param['password'] = $this->md5_salt($param['password']);
            $res = AdminMod::add($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 管理员编辑
     */
    public  function edit()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $find = AdminMod::find($id);
            View::assign('find', $find);
        }
        $role = AdminRole::select();
        View::assign('select', $role);
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(AdminVal::class)->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            if ($param['password'] != '') {
                $param['password'] = $this->md5_salt($param['password']);
            } else {
                unset($param['password']);
            }
            $res = AdminMod::edit($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 管理员删除
     */
    public  function del()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $res = AdminMod::del($id);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(3, $res);
            }
        }
    }
}
